﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Koonsoft.CustomerService.Entity;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace Koonsoft.CustomerService.DAL
{
    public class EmployeeDAL
    {
        private Database database = DatabaseFactory.CreateDatabase("CustomerService");

        public List<Employee> GetEmpolyeeByLoginAccount(string account)
        {
            const string sql = "select * from employees where loginname=@loginname";

            using (var cmd = database.GetSqlStringCommand(sql))
            {
                database.AddInParameter(cmd, "@loginname", DbType.String, account);
                return DataTableToEmpolyees(database.ExecuteDataSet(cmd).Tables[0]);
            }
        }

        public bool UpdagtePassword(string userName,string oldPass,string newPass)
        {
            const string sql = "update employees set password = @newPass  where loginname=@loginname and password = @oldPass";

            using (var cmd = database.GetSqlStringCommand(sql))
            {
                database.AddInParameter(cmd, "@loginname", DbType.String, userName);
                database.AddInParameter(cmd, "@oldPass", DbType.String, oldPass);
                database.AddInParameter(cmd, "@newPass", DbType.String, newPass);
                return database.ExecuteNonQuery(cmd) > 0; 
            }
        }


        private List<Employee> DataTableToEmpolyees(DataTable dt)
        {
            List<Employee> employees = new List<Employee>();

            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    Employee employee = new Employee();
                    employee.EmployeeID = Convert.ToInt32(dr["EmployeeID"]);
                    employee.EmployeeName = dr["EmployeeName"].ToString();
                    employee.LoginName = dr["LoginName"].ToString();
                    employee.Password = dr["Password"].ToString();

                    employees.Add(employee);
                }

                return employees;

            }

            return null;

        }

    }
}
